<template>
  <div class="p-4 space-y-6">
    <h2 class="text-2xl font-bold mb-4 text-blue-400">📊 图表分析</h2>

    <!-- 筛选选项 -->
    <div class="bg-white rounded shadow p-4 space-y-4">
      <div class="flex flex-col md:flex-row md:items-center md:space-x-4 space-y-2 md:space-y-0">
        <label class="font-semibold">时间范围:</label>
        <select v-model="selectedRange" class="border p-2 rounded">
          <option value="all">全部</option>
          <option value="month">本月</option>
          <option value="year">本年</option>
          <option value="custom">自定义</option>
        </select>
      </div>
      <div v-if="selectedRange === 'custom'" class="flex flex-wrap gap-4 items-center">
        <div class="flex items-center space-x-2">
          <label>起始日期:</label>
          <input type="date" v-model="startDate" class="border p-2 rounded" />
        </div>
        <div class="flex items-center space-x-2">
          <label>结束日期:</label>
          <input type="date" v-model="endDate" class="border p-2 rounded" />
        </div>
      </div>
    </div>

    <!-- 概览卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <div class="bg-white rounded shadow p-4 text-center cursor-pointer hover:bg-green-50" @click="openDialog('收入')">
        <h3 class="text-gray-500">总收入</h3>
        <p class="text-green-600 text-xl font-bold">¥{{ totalIncome }}</p>
      </div>
      <div class="bg-white rounded shadow p-4 text-center cursor-pointer hover:bg-red-50" @click="openDialog('支出')">
        <h3 class="text-gray-500">总支出</h3>
        <p class="text-red-500 text-xl font-bold">¥{{ totalExpense }}</p>
      </div>
      <div class="bg-white rounded shadow p-4 text-center">
        <h3 class="text-gray-500">结余</h3>
        <p class="text-blue-600 text-xl font-bold">¥{{ totalIncome - totalExpense }}</p>
      </div>
    </div>


    <!-- 图表区域 -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <!-- 收入 vs 支出 -->
      <div class="bg-white shadow rounded p-4">
        <h3 class="font-semibold mb-2 text-lg">收入 vs 支出</h3>
        <PieChart :data="incomeExpenseChartData" />
      </div>

      <!-- 分类统计 -->
      <div class="bg-white shadow rounded p-4">
        <h3 class="font-semibold mb-2 text-lg">分类统计</h3>
        <BarChart :data="categoryChartData" />
      </div>
    </div>
  </div>
  <!-- 账单明细弹窗 -->
  <transition name="fade">
    <div v-if="showBillDialog" class="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50"
      @click.self="closeDialog">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl p-6 space-y-4">
        <div class="flex justify-between items-center border-b pb-2">
          <div class="text-xl font-bold text-blue-500">
            {{ dialogType }}账单明细
          </div>
          <button @click="closeDialog" class="text-gray-400 hover:text-blue-500 text-2xl">&times;</button>
        </div>
        <div class="overflow-x-auto">
          <table class="min-w-full text-sm text-center">
            <thead class="bg-gray-100">
              <tr>
                <th class="px-3 py-2">时间</th>
                <th class="px-3 py-2">分类</th>
                <th class="px-3 py-2">金额</th>
                <th class="px-3 py-2">备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="bill in pagedDialogBills" :key="bill.id">
                <td class="px-3 py-2">{{ bill.date }}</td>
                <td class="px-3 py-2">{{ bill.category }}</td>
                <td class="px-3 py-2">{{ bill.amount }}</td>
                <td class="px-3 py-2">{{ bill.note }}</td>
              </tr>
              <tr v-if="dialogBills.length === 0">
                <td colspan="4" class="text-gray-400 py-6">暂无账单</td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 分页控件 -->
        <div class="flex justify-center items-center gap-2 mt-2" v-if="dialogPageCount > 1">
          <button class="px-3 py-1 rounded bg-gray-200" :disabled="dialogCurrentPage === 1"
            @click="dialogCurrentPage--">上一页</button>
          <span class="text-base text-gray-700">第 {{ dialogCurrentPage }} / {{ dialogPageCount }} 页</span>
          <button class="px-3 py-1 rounded bg-gray-200" :disabled="dialogCurrentPage === dialogPageCount"
            @click="dialogCurrentPage++">下一页</button>
        </div>
        <div class="text-right pt-2 border-t font-bold">
          合计：<span :class="dialogType === '收入' ? 'text-green-600' : 'text-red-500'">¥{{ dialogTotal }}</span>
        </div>
      </div>
    </div>
  </transition>

</template>

<script setup lang="ts">
import { ref, computed, onMounted,watch } from 'vue'
import axios from 'axios'
import PieChart from '../components/PieChart.vue'
import BarChart from '../components/BarChart.vue'

// Bill 类型修正
interface Bill {
  id: number
  user_id: string
  amount: number
  category: string
  categoryType: string   // 收入 / 支出
  note: string
  date: string
}

const bills = ref<Bill[]>([])
const userId = localStorage.getItem('user_id')
const selectedRange = ref<'all' | 'month' | 'year' | 'custom'>('all')
const startDate = ref('')
const endDate = ref('')

const showBillDialog = ref(false)
const dialogType = ref<'收入' | '支出' | ''>('')
const dialogCurrentPage = ref(1)
const dialogPageSize = 10

const dialogBills = computed(() =>
  filteredBills.value.filter(b => b.categoryType === dialogType.value)
)
const dialogPageCount = computed(() =>
  Math.ceil(dialogBills.value.length / dialogPageSize)
)
const pagedDialogBills = computed(() => {
  const start = (dialogCurrentPage.value - 1) * dialogPageSize
  return dialogBills.value.slice(start, start + dialogPageSize)
})
const dialogTotal = computed(() =>
  dialogBills.value.reduce((sum, b) => sum + b.amount, 0)
)

const openDialog = (type: '收入' | '支出') => {
  dialogType.value = type
  dialogCurrentPage.value = 1
  showBillDialog.value = true
}
const closeDialog = () => {
  showBillDialog.value = false
}

// 获取所有账单
const fetchBills = async () => {
  if (!userId) return
  try {
    const res = await axios.post('http://127.0.0.1:3000/api/get-bills', {
      user_id: userId
    })
    bills.value = res.data.bills as Bill[]
  } catch (err) {
    console.error('获取账单失败', err)
  }
}
onMounted(fetchBills)

// 过滤后的账单（按时间范围）
const filteredBills = computed(() => {
  const now = new Date()
  return bills.value.filter((bill) => {
    // 兼容 "2025-06-01 15:36:44" 这种字符串
    const billDate = new Date(bill.date.replace(' ', 'T'))
    if (selectedRange.value === 'month') {
      return (
        billDate.getFullYear() === now.getFullYear() &&
        billDate.getMonth() === now.getMonth()
      )
    } else if (selectedRange.value === 'year') {
      return billDate.getFullYear() === now.getFullYear()
    } else if (selectedRange.value === 'custom') {
      if (!startDate.value || !endDate.value) return false
      const start = new Date(startDate.value)
      const end = new Date(endDate.value)
      // 仅比对年月日
      const billDateOnly = billDate.toISOString().slice(0, 10)
      return billDateOnly >= startDate.value && billDateOnly <= endDate.value
    }
    return true
  })
})

// 总收入
const totalIncome = computed(() =>
  filteredBills.value
    .filter((b) => b.categoryType === '收入')
    .reduce((sum, b) => sum + b.amount, 0)
)

// 总支出
const totalExpense = computed(() =>
  filteredBills.value
    .filter((b) => b.categoryType === '支出')
    .reduce((sum, b) => sum + b.amount, 0)
)

// 收入 vs 支出图表数据
const incomeExpenseChartData = computed(() => [
  { name: '收入', value: totalIncome.value },
  { name: '支出', value: totalExpense.value }
])

// 分类统计图表数据（合并收入/支出）
const categoryChartData = computed(() => {
  const stats: Record<string, number> = {}
  for (const b of filteredBills.value) {
    if (!stats[b.category]) stats[b.category] = 0
    stats[b.category] += b.amount
  }
  return Object.entries(stats).map(([name, value]) => ({ name, value }))
})

watch(dialogType, () => {
  dialogCurrentPage.value = 1
})

</script>
